package cn.car.biz.impl;

import cn.car.biz.SysRoleBiz;
import cn.car.domains.bo.QueryPermissionBo;
import cn.car.domains.bo.QueryRoleBo;
import cn.car.domains.entity.SysPermissionEntity;
import cn.car.domains.entity.SysRolePermissionRelationEntity;
import cn.car.domains.enums.ActiveStatusEnum;
import cn.car.domains.vo.BasePage;
import cn.car.domains.vo.sysRole.AddPermissionReq;
import cn.car.domains.vo.sysRole.CreateRoleReq;
import cn.car.domains.vo.sysRole.RoleListReq;
import cn.car.domains.vo.sysRole.SysRoleRes;
import cn.car.domains.vo.sysRole.UpdateRoleReq;
import cn.car.domains.entity.SysRoleEntity;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.SysRolePermissionRelationMapper;
import cn.car.service.SysPermissionService;
import cn.car.service.SysRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SysRoleBizImpl implements SysRoleBiz {
    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRolePermissionRelationMapper sysRolePermissionRelationMapper;

    @Resource
    private SysPermissionService sysPermissionService;

    /**
     * 创建角色
     * 将前端传入的CreateRoleReq转换为Entity并调用服务层保存
     */
    @Override
    public void createRole(CreateRoleReq req) {
        SysRoleEntity roleEntity = new SysRoleEntity();
        BeanUtils.copyProperties(req, roleEntity);

        roleEntity.setStatus(ActiveStatusEnum.ACTIVE.name());
        sysRoleService.addRole(roleEntity);
    }

    /**
     * 根据ID获取角色信息
     * 从服务层获取Entity后转换为响应VO
     */
    @Override
    public SysRoleRes getRoleById(Long id) {
        SysRoleEntity roleEntity = sysRoleService.getRoleById(id);
        if (roleEntity == null) {
            return null;
        }
        SysRoleRes res = new SysRoleRes();
        BeanUtils.copyProperties(roleEntity, res);

        return res;
    }

    /**
     * 根据角色编码获取角色信息
     */
    @Override
    public SysRoleRes getRoleByCode(String roleCode) {
        SysRoleEntity roleEntity = sysRoleService.getRoleByCode(roleCode);
        if (roleEntity == null) {
            return null;
        }
        SysRoleRes res = new SysRoleRes();
        BeanUtils.copyProperties(roleEntity, res);
        return res;
    }

    /**
     * 更新角色信息
     */
    @Override
    public void updateRole(UpdateRoleReq req) {
        SysRoleEntity existingRole = sysRoleService.getRoleById(req.getId());
        if (existingRole == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("角色不存在");
        }
        SysRoleEntity updateEntity = new SysRoleEntity();
        BeanUtils.copyProperties(req, updateEntity);
        sysRoleService.updateRole(updateEntity);
    }

    /**
     * 删除角色
     */
    @Override
    public void deleteRole(Long id) {
        SysRoleEntity existingRole = sysRoleService.getRoleById(id);
        if (existingRole == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("角色不存在");
        }
        sysRoleService.deleteRole(id);
    }

    /**
     * 分页查询角色信息
     * 使用PageHelper进行分页，支持角色编码/名称模糊查询
     */
    @Override
    public BasePage<SysRoleRes> list(RoleListReq req) {
        Page<Object> page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        QueryRoleBo query = new QueryRoleBo();
        query.setRoleCode(req.getRoleCode());
        query.setRoleName(req.getRoleName());
        List<SysRoleEntity> roleEntityList = sysRoleService.list(query);
        List<SysRoleRes> resList = roleEntityList.stream().map(entity -> {
            SysRoleRes res = new SysRoleRes();
            BeanUtils.copyProperties(entity, res);
            return res;
        }).toList();
        return BasePage.generateResult(page.getPages(), page.getTotal(), resList);
    }

    @Override
    public void addPermission(AddPermissionReq req) {
        SysRoleEntity sysRoleEntity = sysRoleService.getRoleById(req.getRoleId());

        if (sysRoleEntity == null){
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("角色不存在");
        }

        sysRolePermissionRelationMapper.deleteByRoleId(req.getRoleId());

        QueryPermissionBo queryPermissionBo = new QueryPermissionBo();
        queryPermissionBo.setIds(req.getPermissionIds());
        List<SysPermissionEntity> list = sysPermissionService.list(queryPermissionBo);

        if (list.size() != req.getPermissionIds().size()) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("有权限不存在");
        }

        List<SysRolePermissionRelationEntity> sysRolePermissionRelationEntityList = new ArrayList<>();

        for (Long permissionId : req.getPermissionIds()) {

            SysRolePermissionRelationEntity rolePermissionRelationEntity = new SysRolePermissionRelationEntity();
            rolePermissionRelationEntity.setPermissionId(permissionId);
            rolePermissionRelationEntity.setRoleId(req.getRoleId());
            sysRolePermissionRelationEntityList.add(rolePermissionRelationEntity);
        }

        try {
            sysRolePermissionRelationMapper.batchInsert(sysRolePermissionRelationEntityList);
        } catch (DuplicateKeyException e) {
            log.warn("[角色添加权限] 目前已经有此权限 不需要重复添加");
        }
    }
}
